import React, { Component } from 'react';
import { HashRouter as Router, Route, Switch } from 'react-router-dom';
import Newsmain from './components/Newsmain';
import ReceiveNewsList from './components/ReceiveNewsList';
import Noticedetails from './components/Noticedetails';
import Logidn from '../common/compont/Logidn';
import ErrorTips from '../common/compont/ErrorTips';
import Error from '../common/compont/Error';
import { Spin, message } from 'antd';
import 'antd/dist/antd.css';
import './components/scss/index.scss';
import { createHashHistory } from 'history';
import { getData, postData1, getQueryVariable, axiosMethod } from "../common/js/fetch";
import { lgAlert } from 'lancoo-web-ui';
import '@wangeditor/editor/dist/css/style.css'
import 'lancoo-web-ui/dist/style.css'
import {SKIN_BG_COLOR} from '../hooks/useGetThem'

import { requireSystemTheme, setSystemTheme } from 'lancoo-web-ui';


message.config({
  top: 100,
  duration: 2,
  maxCount: 1,
});

class App extends Component {
  constructor(props) {
    super(props);
    this.state = {
      start: 0,
      sysId: '',
      lockerId: '',
      userT: '',
      init: false,
      skin: 's2'
    };
  }
  alertAInfo2 = () => {
    let alert = lgAlert.show({
      duration: 0,
      content: '您当前的身份没有访问该应用的权限，点击确定返回办公平台',
      tipType: 'info',
      tipSize: 'small',
      tipMouldType: 'A',
      isShowCloseBtn: false,
      showConfirm: false,
      closeText: "知道了",
      onCancel: () => {
        lgAlert.close(alert.index);
        this.openBaseUrl();
      }
    });
  }
  openBaseUrl = () => {
    window.open(sessionStorage.getItem('baseUrl'), '_self');
  }

  componentDidMount() {
    getData('api/common/system/info', { token: sessionStorage.getItem('token') || getQueryVariable('lg_tk') }).then(res => res.json()).then(res => {
      if (res.code == 200 && res.data) {
        sessionStorage.setItem('schoolId', res.data.eduId);
        sessionStorage.setItem('schoolType', '');
        sessionStorage.setItem('schoolName', res.data.eduName);
        sessionStorage.setItem('baseUrl', res.data.baseUrl);
        sessionStorage.setItem('itemUrl', res.data.itemUrl);
        sessionStorage.setItem('sysId', res.data.sysId);
        // sessionStorage.setItem('PsnMgrMainServerAddr', res.data.baseUrl);
        // sessionStorage.setItem('PsnMgrLgAssistantAddr', res.data.itemUrl);

        sessionStorage.setItem('systemInfo', JSON.stringify({
          beEdu: '0',
          iscVersion: res.data.isVersion,
          productName: res.data.productName,
          productType: res.data.productType,
          productUseRange: '3',
          webRootUrl: res.data.baseUrl,
        }))
        this.setState({
          sysId: res.data.sysId,
          lockerId: '',
          start: 1
        })
        console.log('22222222')

        // 获取皮肤值
        // axiosMethod({
        //   url: res.data.baseUrl + 'openapi/v1/system/facade/getSkin',
        //     body: {
        //       appid: '211',
        //       token: getQueryVariable('lg_tk'),
        //     },
        //   showError:false, callback: (skinResult) => {
        //     const { skin: skinInfo = '2' } = skinResult
        //     dispatch({
        //       type: 'SET_SKIN',
        //       data: `s${skinInfo}`
        //     })
        //     setSkin(skinInfo)
        //   }
        // })

        axiosMethod(res.data.baseUrl + 'openapi/v1/system/facade/getSkin', {
          appid: '211',
          token: getQueryVariable('lg_tk'),
        }).then(res => res.json()).then(res => {
          console.log(res)
          if (res.StatusCode == '200') {
            // dispatch({
            //   type: 'SET_SKIN',
            //   data: `s${res.Data.skin}`
            // })
            sessionStorage.setItem('skin', `s${res.Data.skin}`);
            this.setState({
              skin: `s${res.Data.skin}`
            })
          }
        })
       
        getData('api/commons/locker/check', { sysId: this.state.sysId, lockerId: 2, productUseRange: 2, eduId: res.data.eduId }).then(data => {
          return data.json()
        }).then(json => {
          if (json.data && json.data.result == 1) {
            getData('api/common/user', { token: sessionStorage.getItem('token') }).then(data => {
              return data.json()
            }).then(json => {
              if (json.code == 200 && json.data) {
                let { data } = json;
                // 2023-09-14 适配高级管理员
                let identityList = data.identityList;
                let identity = identityList.find(item => item.identityCode === getQueryVariable('lg_ic'))
                console.log(identity,'identity');
                // if (identity?.advanced == 1) {
                //   sessionStorage.setItem('UserType', 0);
                // } else {
                //   sessionStorage.setItem('UserType', data.userType);
                // }
                sessionStorage.setItem('UserType', data.userType);
                sessionStorage.setItem('userInfo', JSON.stringify(data));
                sessionStorage.setItem('UserID', data.userId);
                sessionStorage.setItem('UserName', data.userName);
                sessionStorage.setItem('PhotoPath', data.photoPath);
                sessionStorage.setItem('UserClass', '');
                // sessionStorage.setItem('UserType', data.userType);
                sessionStorage.setItem('iconUrl', data.identityList[0]?.identityCode)
                sessionStorage.setItem('identityName', data.identityList[0]?.identityName)
                sessionStorage.setItem('isPreset', data.identityList[0]?.isPreset)
                sessionStorage.setItem('iconUrl', data.identityList[0]?.identityImg)
                sessionStorage.setItem('PsnMgrToken', getQueryVariable('lg_tk'));

                this.setState({
                  userT: data.userType,
                  init:true
                })

             
                //访问权限校验
                // let url = sessionStorage.getItem('baseUrl') + '/UserMgr/PowerMgr/ValidateIdentity'
                // postData1(url, {
                //   IdentityCode: getQueryVariable('lg_ic'),
                //   ModuleID: 220003,
                //   UserID: data.userId
                // })
                //   .then(res => { return res.json() })
                //   .then(res => {
                //     console.log(res)
                //     if (res.StatusCode == "200" && res.Data == true) {
                //       getData('api/commons/system/server/info', {
                //         sysId: "210"
                //       }).then(data => {
                //         return data.json()
                //       }).then(json => {
                //         if (json.code === "200" && json.data) {
                //           sessionStorage.setItem('PsnMgrLgAssistantAddr', json.data.webSvrAddr);
                //         }
                //       });
                //       getData('api/commons/system/products/info', {
                //       }).then((res) => {
                //         return res.json()
                //       }).then((json) => {
                //         if (json.code == 200) {
                //           sessionStorage.setItem('systemInfo', JSON.stringify(json.data))
                //           this.setState({
                //             start: 1
                //           })
                //           //获取预览系统2023-07-17
                //           if (!sessionStorage.getItem('preview')) {
                //             getData('api/commons/system/server/info', {
                //               sysId: "U10"
                //             }).then((res) => {
                //               return res.json()
                //             }).then((json) => {
                //               if (json.code == 200 && json.data) {
                //                 let data = json.data;
                //                 sessionStorage.setItem('preview', JSON.stringify(data))
                //               } else {
                //                 message.error(json.msg, 3);
                //               }
                //             })
                //           }
                //         } else {
                //           message.error(json.msg, 3);
                //         }
                //       })
                //     } else {
                //       this.alertAInfo2();
                //     }
                //   })
                  // getData('api/commons/system/server/info', {
                  //   sysId: "264"
                  // }).then(data => {
                  //   return data.json()
                  // }).then(json => {
                  //   if (json.code === "200" && json.data) {
                  //     sessionStorage.setItem('PsnMgrLgAssistantAddr', json.data.webSvrAddr);
                  //   }
                  // });
                  getData('api/common/system/info', {
                  }).then((res) => {
                    return res.json()
                  }).then((json) => {
                    if (json.code == 200) {
                      sessionStorage.setItem('systemInfo', JSON.stringify(json.data))
                      this.setState({
                        start: 1
                      })
                      //获取预览系统2023-07-17
                      if (!sessionStorage.getItem('preview')) {
                        getData('api/common/system/list', {
                          sysIds: "U10"
                        }).then((res) => {
                          return res.json()
                        }).then((json) => {
                          if (json.code == 200 && json.data) {
                            let data = json.data;
                            sessionStorage.setItem('preview', JSON.stringify(data))
                          } else {
                            message.error(json.msg, 3);
                          }
                        })
                      }
                    } else {
                      message.error(json.msg, 3);
                    }
                  })

              }
              else {
                let url = window.location.href;
                url = url.split('?');
                if (url.length > 1 && url[1].indexOf('&') > -1) {
                  let pram = url[1].split('&');
                  url = url[0] + '?';
                  pram.map((item) => {
                    if (item.indexOf('lg_tk=') === -1) {
                      url += item + '&';
                    }
                  })
                  url = url.slice(0, -1);
                } else {
                  url = url[0];
                }
                if (url.slice(-2) == '#/') {
                  url = url.slice(0, -2);
                }
                url = encodeURIComponent(url);
                sessionStorage.removeItem('token');

                // sessionStorage.removeItem('PsnMgrToken');
                getData('api/commons/school/system/info', {
                  schoolId: sessionStorage.getItem('schoolId')
                },
                ).then((res) => {
                  return res.json();
                }).then((json) => {
                  // console.log(json.data.baseUrl + '/UserMgr/Login/Login.aspx?lg_sysid=' + json.data.noticeSysId + '&lg_preurl=' + url);
                  // alert('未认证用户信息，请重新登录~');

                  // window.open(json.data.baseUrl + '/UserMgr/Login/Login.aspx?lg_sysid=' + json.data.noticeSysId + '&lg_preurl=' + url, '_self');
                  window.open(json.data.baseUrl + '?lg_sysid=' + json.data.noticeSysId + '&lg_preurl=' + url, '_self');
                  // window.open(json.data.baseUrl + '/UserMgr/Login/Login.aspx?lg_sysid=' + json.data.noticeSysId , '_self');
                })
              }
            })
          } else {
            // console.log(1231313);
            if (json.data.result !== 1) {
              window.open(json.data.lockErrAddr + json.data.result, "_self");
            }
          }
        })
      }
    })
  }
  render() {
    let basicPlatformAddress = sessionStorage.getItem("baseUrl"); //基础平台地址
    let appId = '264'; //子系统ID
    let token = sessionStorage.getItem("token"); //用户令牌
    console.log(basicPlatformAddress)
    
    /**
     * @description  : 此处用于非代理下的子系统，如另外需要部署的子系统调用；可以参考一卡通
     * @waring  : 注：此方法有请求，会导致部分系统产生跨域无法正常调用的情况，请子系统对接基础平台后参考调用形式四
     * @waring  : 注：如果控制台打印 “[web-ui] 缓存未获取到用户主题,请自行调用设置主题色工具,如已添加请忽略此打印” 请用此方法；
    
    */
    // eslint-disable-next-line no-unused-expressions
    window?._defaultThemeColor?.error(() => requireSystemTheme(basicPlatformAddress, appId, token))
    // requireSystemTheme(basicPlatformAddress, appId, token);
    if(!this.state.init){
      
      return <div><Spin size="large" /></div>
    }
    
    return (
      <div style={{
        backgroundColor:SKIN_BG_COLOR[`${this.state.skin}`]
    }}>
        {this.state.start === 1 ? <div>
          <div>

            {/* <Search></Search> */}
            <Router>
              {/* exact表示绝对匹配 */}
              {/* 在react-router中每一个Route相当于一个组件 */}
              {/* 在传递参数的时候可以设置成 :参数名? 表示可选参数 */}
              {/* Switch表示只匹配一个符合条件的路由 */}
              <Switch>
                {/* <Route path="/AnswerInfo" component={AnswerInfo} />
                <Route path="/EditQue" component={EditQue} />
                <Route path="/GetQtnContent" component={GetQtnContent} /> */}
                <Route path="/RecNewsContent" component={Noticedetails} />
                <Route path="/NewsContent" component={Noticedetails} />
                <Route path="/ReceiveNewsList" component={ReceiveNewsList} />
                {/* <Route path="/" exact component={this.state.userT === '6' ? Newsmain : ReceiveNewsList} /> */}
                {
                  getQueryVariable('isManage')  == 1 ? 
                  <Route path="/" exact component={Newsmain} /> : 
                  <Route path="/" exact component={ReceiveNewsList} />
                }
                <Route path="/Error" component={Error} />
                <Route path="/ErrorTips" component={ErrorTips} />
                {/* <Route path="/hot_show" component={() => <h1>热映 </h1>} /> */}
                {/* <Route path="/detail/:id" component={() => <h1>详情页</h1>} /> */}
                <Route component={Logidn} />
              </Switch>
            </Router>
          </div>
        </div> : ''}
        <div className="example" style={{ display: 'none', height: document.documentElement.clientHeight + 'px', lineHeight: document.documentElement.clientHeight + 'px' }}> <Spin size="large" /></div>
      </div>
    );
  }
}
export default App;